//
//  Material.swift
//  物料商行
//
//  Created by HaoDong Hong on 2017/9/11.
//  Copyright © 2017年 HaoDong Hong. All rights reserved.
//

import Foundation
import SwiftyJSON
import Alamofire

enum RequestError: Error {
    case error(message: String)
}

struct Material {
    var name: String
    var productCode: String
    var materialId: Int
    var coverImage: String
}
struct MaterialStyle {
    var id: Int
    var name: String
    var pid: Int
}


struct MaterialColor: CustomStringConvertible {
    var no: String
    var color: UIColor
    var stock: String
    var picture: String
    var description: String {
        return ""
    }
}

enum MaterialRequest: RequestProtocol {
    var host: String {
        switch self {
        case .dingyueRecord():
            return "http://120.25.176.231:8000/seller-material/store/"
        default:
            return "http://120.25.176.231:8000/seller-material/material/"
        }
    }
    case allMaterials(id: Int)
    case topStyles
    case nextStyles(id: Int)
    case createPicture(base64code: String)
    
    case create(data: Data)
    
    case editMaterial()
    case find(id: Int)
    //case edit
    case delete(id: [Int])
    case changeClass(materialIds: [Int], classId: Int)
    
    case getMaterialDetail(materialId: Int)
    // 入库面料
    case input()
    // 获得入库记录数据
    case rukuRecord()
    // 销售面料
    case sale()
    // 获得销售记录数据
    case saleRecord()
    
    // 设置是否能索版
    case suoban(materialId: Int, status: Int)
    
    // 获得索版记录数据
    case suobanRecord()
    
    // 获得商家被买家订阅的记录
    case dingyueRecord()
    
    case shareMaterial(materialId: Int, scanMaterialId: Int)
    
    // 获得共享记录
    case shareRecord(materialId: Int)
    
    // 设置是否零卖
    case setLingMai(materialId: Int, status: Int, price: Double?)
    
    // 创建授信白条
    case createShouXin()
    
    // 查看授信记录
    case getShouXinRecord(type: Int)
    
    // 欠款记录
    case getIndebtRecord()
    
    
    var bodyParams: Parameters {
        switch self {
        case .allMaterials(let id):
            return ["sessionId": Store.sessionID!, "storeId": Store.storeId!, "classId": id]
        case .topStyles:
            return ["sessionId": Store.sessionID!, "storeId": Store.storeId!]
        case .nextStyles(let id):
            return ["sessionId": Store.sessionID!, "storeId": Store.storeId!, "pid": id]
        case .createPicture(let base64code):
            return ["sessionId": Store.sessionID!, "storeId": Store.storeId!, "base64code": base64code]
            
        case .find(let id):
            return ["sessionId": Store.sessionID!, "storeId": Store.storeId!, "materialId": id]
        case .delete(let ids):
            let json = """
            {
            "ids": \(ids)
            }
            """
            return ["sessionId": Store.sessionID!, "storeId": Store.storeId!, "materialIds": json]
            
        case .changeClass(let materialIds, let classId):
            let json = """
            {
            "ids": \(materialIds)
            }
            """
            
            return ["sessionId": Store.sessionID!, "storeId": Store.storeId!, "materialIds": json, "classId": classId]
            
        case .create(_):
            return ["": ""]
        case .editMaterial():
            return ["": ""]
        case .getMaterialDetail(let materialId):
            return ["sessionId": Store.sessionID!, "storeId": Store.storeId!, "materialId": materialId]
        case .input():
            return ["": ""]
        case .rukuRecord():
            return ["": ""]
        case .sale():
            return ["": ""]
        case .saleRecord():
            return ["": ""]
        case .suoban(let materialId, let status):
            return ["sessionId": Store.sessionID!, "storeId": Store.storeId!, "materialId": materialId, "status": status]
        case .suobanRecord():
            return ["": ""]
        case .dingyueRecord():
            return ["sessionId": Store.sessionID!, "storeId": Store.storeId!]
        case .shareMaterial(let materialId, let scanMaterialId):
            return ["sessionId": Store.sessionID!, "storeId": Store.storeId!, "materialId": materialId, "scanmaterialId": scanMaterialId]
        case .shareRecord(let materialId):
            return ["sessionId": Store.sessionID!, "storeId": Store.storeId!, "materialId": materialId]
        case .setLingMai(let materialId, let status, let price):
            return ["sessionId": Store.sessionID!, "storeId": Store.storeId!, "materialId": materialId, "status": status, "price": price ?? 0]
        case .createShouXin():
            return ["": ""]
        case .getShouXinRecord(let type):
            return ["sessionId": Store.sessionID!, "storeId": Store.storeId!, "type": type]
        case .getIndebtRecord():
            return ["sessionId": Store.sessionID!, "storeId": Store.storeId!]
        }
    }
    var path: String {
        switch self {
        case .allMaterials(_):
            return "findall"
        case .topStyles:
            return "get_top_styles"
        case .nextStyles(_):
            return "get_next_styles"
        case .createPicture(_):
            return "create-picture"
        case .find(_):
            return "find"
        case .delete(_):
            return "delete"
        case .changeClass(_, _):
            return "changeclass"
        case .create(_):
            return "create"
        case .editMaterial():
            return "edit"
        case .getMaterialDetail(_):
            return "find"
        case .input():
            return "input"
        case .rukuRecord():
            return "record"
        case .sale():
            return "sale"
        case .saleRecord():
            return "salerecord"
        case .suoban(_, _):
            return "set/suoban"
        case .suobanRecord():
            return "suobanrecord"
        case .dingyueRecord():
            return "subscribe/myrecord"
        case .shareMaterial(_, _):
            return "share"
        case .shareRecord(_):
            return "sharerecord"
        case .setLingMai(_,_,_):
            return "set/lingmai"
        case .createShouXin():
            return "credit/create"
        case .getShouXinRecord(_):
            return "credit/findall"
        case .getIndebtRecord():
            return "credit/findallindebt"
        }
    }
    
    var fullURL: URL {
        let str = self.host + self.path
        return URL(string: str)!
    }
}

class MaterialHelper {
    private var request: MaterialRequest = .topStyles
    private func dataRequest(from request: RequestProtocol) -> DataRequest {
        //return Alamofire.request(request.fullURL, method: .post, parameters: request.bodyParams, encoding: URLEncoding.httpbody)
        return Alamofire.request(request.fullURL, method: request.method, parameters: request.bodyParams, encoding: URLEncoding.httpBody, headers: nil)
        //return Alamofire.request(request.fullURL, method: request.method, parameters: request.bodyParams, encoding: URLEncoding.httpbody, headers: nil)
    }
    private func DataRequest(from request: RequestProtocol, with data: Data) -> DataRequest {
        var _request = URLRequest(url: request.fullURL)
        _request.httpMethod = request.method.rawValue
        _request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        _request.httpBody = data
        return Alamofire.request(_request)
    }
    
    func getAllMaterials(with id: Int, completeHandler: @escaping (Bool, [Material]?) -> Void) {
        request = .allMaterials(id: id)
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(false, nil)
                }
                return
            }
            let json = JSON(result)
            guard json["status"].intValue == 200 else {
                assertionFailure(json["errmsg"].stringValue)
                DispatchQueue.main.async {
                    completeHandler(false, nil)
                }
                return
            }
            let data = json["data"].arrayValue
            var materials = [Material]()
            for item in data {
                let materialId = item["materialId"].intValue
                let name = item["name"].stringValue
                let productCode = item["no"].stringValue
                let coverImage = item["cover"].stringValue
                materials.append(Material(name: name, productCode: productCode, materialId: materialId, coverImage: coverImage))
            }
            DispatchQueue.main.async {
                completeHandler(true, materials)
            }
        }
    }
    
    func changeClass(to classId: Int, materialIds: [Int], completeHandler: @escaping (Bool) -> Void) {
        request = .changeClass(materialIds: materialIds, classId: classId)
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(false)
                }
                return
            }
            let json = JSON(result)
            let status = json["status"].intValue
            guard status == 200 else {
                DispatchQueue.main.async {
                    completeHandler(false)
                }
                return
            }
            let errorIds = json["errmsg"]["error_ids"].arrayValue
            guard errorIds.count == 0 else {
                DispatchQueue.main.async {
                    completeHandler(false)
                }
                return
            }
            DispatchQueue.main.async {
                completeHandler(true)
            }
        }
    }
    
    func deleteMaterials(ids: [Int], completeHandler: @escaping (Bool) -> Void ) {
        request = .delete(id: ids)
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(false)
                }
                return
            }
            let json = JSON(result)
            let status = json["status"].intValue
            guard status == 200 else {
                DispatchQueue.main.async {
                    completeHandler(false)
                }
                return
            }
            let errorIds = json["errmsg"]["error_ids"].arrayValue
            guard errorIds.count == 0 else {
                DispatchQueue.main.async {
                    completeHandler(false)
                }
                return
            }
            DispatchQueue.main.async {
                completeHandler(true)
            }
        }
    }
    
    func getTopStyles(completeHandler: @escaping (RequestError?, [MaterialStyle]?) -> Void) {
        request = .topStyles
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: "没有Value"), nil)
                }
                return
            }
            let json = JSON(result)
            let status = json["status"].intValue
            guard status == 200 else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: json["errmsg"].stringValue), nil)
                }
                return
            }
            let data = json["data"].arrayValue
            var materialStyles = [MaterialStyle]()
            guard data.count > 0 else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: "no more data"), nil)
                }
                return
            }
            for item in data {
                let id = item["id"].intValue
                let name = item["name"].stringValue
                let pid = item["pid"].intValue
                materialStyles.append(MaterialStyle(id: id, name: name, pid: pid))
            }
            DispatchQueue.main.async {
                completeHandler(nil, materialStyles)
            }
        }
    }
    
    func getNextStyles(from styleId: Int, completeHandler: @escaping (RequestError?, [MaterialStyle]?) -> Void) {
        request = .nextStyles(id: styleId)
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: "没有Value"), nil)
                }
                return
            }
            let json = JSON(result)
            let status = json["status"].intValue
            guard status == 200 else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: json["errmsg"].stringValue), nil)
                }
                return
            }
            let data = json["data"].arrayValue
            var materialStyles = [MaterialStyle]()
            guard data.count > 0 else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: "no more data"), nil)
                }
                return
            }
            for item in data {
                let id = item["id"].intValue
                let name = item["name"].stringValue
                let pid = item["pid"].intValue
                materialStyles.append(MaterialStyle(id: id, name: name, pid: pid))
            }
            DispatchQueue.main.async {
                completeHandler(nil, materialStyles)
            }
        }
    }
    
    func createPicture(base64code: String, completeHandler: @escaping (RequestError?, String?) -> Void) {
        request = .createPicture(base64code: base64code)
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                completeHandler(RequestError.error(message: "没有Value"), nil)
                return
            }
            let json = JSON(result)
            let status = json["status"].intValue
            guard status == 200 else {
                completeHandler(RequestError.error(message: json["errmsg"].stringValue), nil)
                return
            }
            let url = json["data"]["url"].stringValue
            guard let _ = URL(string: url) else {
                completeHandler(RequestError.error(message: "url convert 失败"), nil)
                return
            }
            completeHandler(nil, url)
        }
    }
    
    func createMaterial(data: Data, completeHandler: @escaping (RequestError?, Int?) -> Void) {
        request = .create(data: data)
        var createRequest = URLRequest(url: request.fullURL)
        createRequest.httpMethod = request.method.rawValue
        createRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
        createRequest.httpBody = data
        Alamofire.request(createRequest).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: "没有Value"), nil)
                }
                return
            }
            let json = JSON(result)
            let status = json["status"].intValue
            guard status == 200 else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: json["errmsg"].stringValue), nil)
                }
                return
            }
            let materialId = json["data"]["materialId"].int
            DispatchQueue.main.async {
                completeHandler(nil, materialId)
            }
        }
    }
    
    func editMaterial(data: Data, completeHandler: @escaping (RequestError?) -> Void) {
        request = .editMaterial()
        DataRequest(from: request, with: data).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: "没有Value"))
                }
                return
            }
            let json = JSON(result)
            let status = json["status"].intValue
            guard status == 200 else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: json["errmsg"].stringValue))
                }
                return
            }
            DispatchQueue.main.async {
                completeHandler(nil)
            }
        }
    }
    func getMaterialDetail(with materialId: Int, completeHandler: @escaping (RequestError?, MaterialDetail?) -> Void) {
        request = .getMaterialDetail(materialId: materialId)
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: "没有Value"), nil)
                }
                return
            }
            let json = JSON(result)
            let status = json["status"].intValue
            guard status == 200 else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: json["errmsg"].stringValue), nil)
                }
                return
            }
            let jsonString = json["data"].rawString()!
            let jsonData = jsonString.data(using: .utf8)!
            let decoder = JSONDecoder()
            let materialDetail = try! decoder.decode(MaterialDetail.self, from: jsonData)
            DispatchQueue.main.async {
                completeHandler(nil, materialDetail)
            }
        }
    }
    func input(with data: Data, completeHandler: @escaping (RequestError?) -> Void) {
        request = .input()
        var createRequest = URLRequest(url: request.fullURL)
        createRequest.httpMethod = request.method.rawValue
        createRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
        createRequest.httpBody = data
        Alamofire.request(createRequest).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: "没有Value"))
                }
                return
            }
            let json = JSON(result)
            let status = json["status"].intValue
            guard status == 200 else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: json["errmsg"].stringValue))
                }
                return
            }
            DispatchQueue.main.async {
                completeHandler(nil)
            }
        }
    }

    func getRuKuRecord(with data: Data, completeHandler: @escaping (RequestError?, [RuKuRecord]?) -> Void) {
        request = .rukuRecord()
        DataRequest(from: request, with: data).responseJSON { (response) in
            
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: "没有Value"), nil)
                }
                return
            }
            let json = JSON(result)
            let status = json["status"].intValue
            guard status == 200 else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: json["errmsg"].stringValue), nil)
                }
                return
            }
            let jsonString = json["data"]["list"].rawString()!
            let jsonData = jsonString.data(using: .utf8)!
            let decoder = JSONDecoder()
            let records = try! decoder.decode([RuKuRecord].self, from: jsonData)
            DispatchQueue.main.async {
                completeHandler(nil, records)
            }
        }
    }
    
    //销售面料
    func saleMaterial(with data: Data, completeHandler: @escaping (RequestError?) -> Void) {
        request = .sale()
        DataRequest(from: request, with: data).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: "没有Value"))
                }
                return
            }
            let json = JSON(result)
            let status = json["status"].intValue
            print(json)
            guard status == 200 else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: json["errmsg"].stringValue))
                }
                return
            }
            DispatchQueue.main.async {
                completeHandler(nil)
            }
        }
    }
    
    
    func getSaleRecord(with data: Data, completeHandler: @escaping (RequestError?, [SaleRecord]?) -> Void) {
        request = .saleRecord()
        DataRequest(from: request, with: data).responseJSON { (response) in
            
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: "没有Value"), nil)
                }
                return
            }
            let json = JSON(result)
            let status = json["status"].intValue
            guard status == 200 else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: json["errmsg"].stringValue), nil)
                }
                return
            }
            let jsonString = json["data"]["list"].rawString()!
            let jsonData = jsonString.data(using: .utf8)!
            let decoder = JSONDecoder()
            let records = try! decoder.decode([SaleRecord].self, from: jsonData)
            DispatchQueue.main.async {
                completeHandler(nil, records)
            }
        }
    }
    func setSuoBan(with materialId: Int, status: Int, completeHandler: @escaping (RequestError?) -> Void) {
        request = .suoban(materialId: materialId, status: status)
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: "没有Value"))
                }
                return
            }
            let json = JSON(result)
            let status = json["status"].intValue
            guard status == 200 else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: json["errmsg"].stringValue))
                }
                return
            }
            DispatchQueue.main.async {
                completeHandler(nil)
            }
        }
    }
    func getSuobanRecord(with data: Data, completeHandler: @escaping (RequestError?, [SuoBanRecord]?) -> Void) {
        request = .suobanRecord()
        DataRequest(from: request, with: data).responseJSON { (response) in
            
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: "没有Value"), nil)
                }
                return
            }
            let json = JSON(result)
            let status = json["status"].intValue
            guard status == 200 else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: json["errmsg"].stringValue), nil)
                }
                return
            }
            let jsonString = json["data"]["list"].rawString()!
            let jsonData = jsonString.data(using: .utf8)!
            let decoder = JSONDecoder()
            let records = try! decoder.decode([SuoBanRecord].self, from: jsonData)
            DispatchQueue.main.async {
                completeHandler(nil, records)
            }
        }
    }

    func getDingYueRecord(completeHandler: @escaping (RequestError?, [DingYueRecord]?) -> Void) {
        request = .dingyueRecord()
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: "没有Value"), nil)
                }
                return
            }
            let json = JSON(result)
            let status = json["status"].intValue
            guard status == 200 else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: json["errmsg"].stringValue), nil)
                }
                return
            }
            let jsonString = json["data"].rawString()!
            let jsonData = jsonString.data(using: .utf8)!
            let decoder = JSONDecoder()
            let records = try! decoder.decode([DingYueRecord].self, from: jsonData)
            DispatchQueue.main.async {
                completeHandler(nil, records)
            }
        }
    }
    func shareMaterial(materialId: Int, scanMaterialId: Int, completeHandler: @escaping (RequestError?) -> Void) {
        request = .shareMaterial(materialId: materialId, scanMaterialId: scanMaterialId)
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: "没有Value"))
                }
                return
            }
            let json = JSON(result)
            let status = json["status"].intValue
            guard status == 200 else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: json["errmsg"].stringValue))
                }
                return
            }
            DispatchQueue.main.async {
                completeHandler(nil)
            }
        }
    }
    
    func getShareRecord(materialId: Int, completeHandler: @escaping (RequestError?, [ShareRecord]?) -> Void) {
        request = .shareRecord(materialId: materialId)
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: "没有Value"), nil)
                }
                return
            }
            let json = JSON(result)
            let status = json["status"].intValue
            guard status == 200 else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: json["errmsg"].stringValue), nil)
                }
                return
            }
            let jsonString = json["data"]["list"].rawString()!
            let jsonData = jsonString.data(using: .utf8)!
            let decoder = JSONDecoder()
            let records = try! decoder.decode([ShareRecord].self, from: jsonData)
            DispatchQueue.main.async {
                completeHandler(nil, records)
            }
        }
    }
    func setLingMain(with materialId: Int, status: Int, price: Double?, completeHandler: @escaping (RequestError?) -> Void) {
        request = .setLingMai(materialId: materialId, status: status, price: price)
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: "没有Value"))
                }
                return
            }
            let json = JSON(result)
            let status = json["status"].intValue
            guard status == 200 else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: json["errmsg"].stringValue))
                }
                return
            }
            DispatchQueue.main.async {
                completeHandler(nil)
            }
        }
    }
    
    func createShouXin(with credit: ShouXinRoot, completeHandler: @escaping (RequestError?) -> Void) {
        let encoder = JSONEncoder()
        let data = try! encoder.encode(credit)
        request = .createShouXin()
        DataRequest(from: request, with: data).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: "没有Value"))
                }
                return
            }
            let json = JSON(result)
            let status = json["status"].intValue
            guard status == 200 else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: json["errmsg"].stringValue))
                }
                return
            }
            DispatchQueue.main.async {
                completeHandler(nil)
            }
        }
    }
    
    /// type: 1代表卖家，2代表买家
    func getShouXinRecord(with type: Int, completeHandler: @escaping (RequestError?, [ShouXinRecord]?) -> Void) {
        request = .getShouXinRecord(type: type)
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: "没有Value"), nil)
                }
                return
            }
            let json = JSON(result)
            let status = json["status"].intValue
            guard status == 200 else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: json["errmsg"].stringValue), nil)
                }
                return
            }
            let jsonString = json["data"]["list"].rawString()!
            let jsonData = jsonString.data(using: .utf8)!
            let decoder = JSONDecoder()
            if type == 1 {
                let records = try! decoder.decode([SalerShouXinRecord].self, from: jsonData)
                DispatchQueue.main.async {
                    completeHandler(nil, records)
                }
            } else {
                let records = try! decoder.decode([BuyerShouXinRecord].self, from: jsonData)
                DispatchQueue.main.async {
                    completeHandler(nil, records)
                }
            }
        }
    }
    func getIndebt(completeHandler: @escaping (RequestError?, [IndebtRecord]?) -> Void) {
        request = .getIndebtRecord()
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: "没有Value"), nil)
                }
                return
            }
            let json = JSON(result)
            let status = json["status"].intValue
            guard status == 200 else {
                DispatchQueue.main.async {
                    completeHandler(RequestError.error(message: json["errmsg"].stringValue), nil)
                }
                return
            }
            let jsonString = json["data"]["list"].rawString()!
            let jsonData = jsonString.data(using: .utf8)!
            let decoder = JSONDecoder()
            let records = try! decoder.decode([IndebtRecord].self, from: jsonData)
            DispatchQueue.main.async {
                completeHandler(nil, records)
            }
        }
    }
    
}

